import calUserAPI from "@/api/acl/user"
const getDefaultState = () => {
  return {
    total: 0,
    userInfo: [],
    allRolesList: [],
    assignRoles: []
  }
}

const state = getDefaultState()

const mutations = {
  SET_TOTAL: (state, total) => {
    state.total = total
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ALLROLESLIST: (state, allRolesList) => {
    state.allRolesList = allRolesList
  },
  SET_ASSIGNROLES: (state, assignRoles) => {
    state.assignRoles = assignRoles
  }
}

const actions = {
  //获取用户管理信息
  async getCalUserInfo({ commit }, { page, limit, username }) {
    try {
      let result = await calUserAPI.reqPageUserData(page, limit, username)
      let { total, items } = result.data
      commit('SET_TOTAL', total)
      commit('SET_USERINFO', items)
    } catch (error) {
      console.log(error)
    }
  },

  //根据用户获取角色数据
  async getRoleData({ commit }, userId) {
    try {
      let result = await calUserAPI.reqUserRoleData(userId)
      commit('SET_ALLROLESLIST', result.data.allRolesList)
      commit('SET_ASSIGNROLES', result.data.assignRoles.map(item => item.id))
    } catch (error) {
      console.log(error)
    }
  },
  //根据全选全部选设置assignRoles
  setAssignRoles({ commit }, { assignRoles, allRolesList }) {
    if (typeof assignRoles === 'boolean') {
      assignRoles ? commit('SET_ASSIGNROLES', allRolesList) : commit('SET_ASSIGNROLES', [])
    } else {
      // console.log(assignRoles)
      commit('SET_ASSIGNROLES', assignRoles)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

